/**
 * 作文服务层
 * 处理作文相关的业务逻辑
 */

import { Essay, User, sequelize, Sequelize } from '../models/index.js';
import { AppError } from '../utils/appError.js';

const { Op } = Sequelize;

/**
 * 创建新作文
 * @param {string} userId - 用户ID
 * @param {string} title - 作文标题
 * @param {string} content - 作文内容
 * @param {string} gradeLevel - 年级级别
 * @returns {Promise<{success: boolean, data: object, message: string}>}
 */
export const createEssay = async (userId, title, content, gradeLevel) => {
  // 1. 输入验证
  if (!userId || typeof userId !== 'string') {
    throw new AppError('INVALID_INPUT', '用户ID不能为空', 400);
  }

  if (!title || typeof title !== 'string' || title.trim().length === 0) {
    throw new AppError('INVALID_INPUT', '标题不能为空', 400);
  }

  if (title.length < 1 || title.length > 200) {
    throw new AppError('INVALID_INPUT', '标题长度必须在1-200个字符之间', 400);
  }

  if (!content || typeof content !== 'string' || content.trim().length === 0) {
    throw new AppError('INVALID_INPUT', '内容不能为空', 400);
  }

  if (content.length < 50 || content.length > 5000) {
    throw new AppError('INVALID_INPUT', '内容长度必须在50-5000个字符之间', 400);
  }

  const validGradeLevels = ['primary', 'middle', 'high'];
  if (!gradeLevel || !validGradeLevels.includes(gradeLevel)) {
    throw new AppError('INVALID_INPUT', '年级级别必须是: primary, middle, high 之一', 400);
  }

  // 2. 验证用户是否存在
  const user = await User.findByPk(userId);
  if (!user) {
    throw new AppError('USER_NOT_FOUND', '用户不存在', 404);
  }

  // 3. 创建作文（使用事务）
  const transaction = await sequelize.transaction();
  try {
    const essay = await Essay.create(
      {
        userId,
        title: title.trim(),
        content: content.trim(),
        gradeLevel,
        status: 'pending', // 默认状态为待批改
      },
      { transaction }
    );

    await transaction.commit();

    // 4. 返回创建的作文（包含用户信息）
    const essayWithUser = await Essay.findByPk(essay.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'gradeLevel'],
        },
      ],
    });

    return {
      success: true,
      data: essayWithUser.toJSON(),
      message: '作文提交成功',
    };
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
};

/**
 * 根据ID获取作文
 * @param {string} essayId - 作文ID
 * @returns {Promise<{success: boolean, data: object, message: string}>}
 */
export const getEssayById = async (essayId) => {
  // 1. 输入验证
  if (!essayId || typeof essayId !== 'string') {
    throw new AppError('INVALID_INPUT', '作文ID不能为空', 400);
  }

  // 2. 查询作文
  const essay = await Essay.findByPk(essayId, {
    include: [
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'gradeLevel'],
      },
    ],
  });

  if (!essay) {
    throw new AppError('ESSAY_NOT_FOUND', '作文不存在', 404);
  }

  // 3. 返回作文信息
  return {
    success: true,
    data: essay.toJSON(),
    message: '获取作文成功',
  };
};

/**
 * 获取用户的作文列表
 * @param {string} userId - 用户ID
 * @param {object} filters - 过滤条件
 * @param {number} filters.limit - 每页数量
 * @param {number} filters.offset - 偏移量
 * @param {string} filters.gradeLevel - 年级级别过滤
 * @param {string} filters.status - 状态过滤
 * @param {object} filters.dateRange - 日期范围过滤
 * @param {Date} filters.dateRange.start - 起始日期
 * @param {Date} filters.dateRange.end - 结束日期
 * @returns {Promise<{success: boolean, data: {essays: array, total: number}, message: string}>}
 */
export const getUserEssays = async (userId, filters = {}) => {
  // 1. 输入验证
  if (!userId || typeof userId !== 'string') {
    throw new AppError('INVALID_INPUT', '用户ID不能为空', 400);
  }

  // 2. 验证用户是否存在
  const user = await User.findByPk(userId);
  if (!user) {
    throw new AppError('USER_NOT_FOUND', '用户不存在', 404);
  }

  // 3. 构建查询条件
  const where = { userId };

  // 添加年级过滤
  if (filters.gradeLevel) {
    const validGradeLevels = ['primary', 'middle', 'high'];
    if (!validGradeLevels.includes(filters.gradeLevel)) {
      throw new AppError('INVALID_INPUT', '年级级别必须是: primary, middle, high 之一', 400);
    }
    where.gradeLevel = filters.gradeLevel;
  }

  // 添加状态过滤
  if (filters.status) {
    const validStatuses = ['pending', 'processing', 'completed', 'failed'];
    if (!validStatuses.includes(filters.status)) {
      throw new AppError('INVALID_INPUT', '状态必须是: pending, processing, completed, failed 之一', 400);
    }
    where.status = filters.status;
  }

  // 添加日期范围过滤
  if (filters.dateRange) {
    const { start, end } = filters.dateRange;
    if (start || end) {
      where.updatedAt = {};
      if (start) {
        where.updatedAt[Op.gte] = start; // 大于等于起始日期
      }
      if (end) {
        where.updatedAt[Op.lte] = end; // 小于等于结束日期
      }
    }
  }

  // 4. 分页参数
  const limit = filters.limit !== undefined ? parseInt(filters.limit) : 10;
  const offset = filters.offset !== undefined ? parseInt(filters.offset) : 0;

  if (isNaN(limit) || limit < 1 || limit > 100) {
    throw new AppError('INVALID_INPUT', '每页数量必须在1-100之间', 400);
  }

  if (isNaN(offset) || offset < 0) {
    throw new AppError('INVALID_INPUT', '偏移量不能为负数', 400);
  }

  // 5. 查询作文列表
  const { count, rows } = await Essay.findAndCountAll({
    where,
    limit,
    offset,
    order: [['createdAt', 'DESC']], // 按创建时间倒序
    include: [
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'gradeLevel'],
      },
    ],
  });

  // 6. 返回结果
  return {
    success: true,
    data: {
      essays: rows.map((essay) => essay.toJSON()),
      total: count,
      limit,
      offset,
    },
    message: '获取作文列表成功',
  };
};

/**
 * 更新作文
 * @param {string} essayId - 作文ID
 * @param {string} userId - 用户ID（用于权限验证）
 * @param {object} updates - 更新内容
 * @param {string} updates.title - 新标题
 * @param {string} updates.content - 新内容
 * @param {string} updates.gradeLevel - 新年级级别
 * @returns {Promise<{success: boolean, data: object, message: string}>}
 */
export const updateEssay = async (essayId, userId, updates) => {
  // 1. 输入验证
  if (!essayId || typeof essayId !== 'string') {
    throw new AppError('INVALID_INPUT', '作文ID不能为空', 400);
  }

  if (!userId || typeof userId !== 'string') {
    throw new AppError('INVALID_INPUT', '用户ID不能为空', 400);
  }

  if (!updates || typeof updates !== 'object' || Object.keys(updates).length === 0) {
    throw new AppError('INVALID_INPUT', '更新内容不能为空', 400);
  }

  // 2. 查询作文
  const essay = await Essay.findByPk(essayId);
  if (!essay) {
    throw new AppError('ESSAY_NOT_FOUND', '作文不存在', 404);
  }

  // 3. 验证用户所有权
  if (essay.userId !== userId) {
    throw new AppError('FORBIDDEN', '无权修改此作文', 403);
  }

  // 4. 构建更新数据
  const updateData = {};

  if (updates.title !== undefined) {
    if (typeof updates.title !== 'string' || updates.title.trim().length === 0) {
      throw new AppError('INVALID_INPUT', '标题不能为空', 400);
    }
    if (updates.title.length < 1 || updates.title.length > 200) {
      throw new AppError('INVALID_INPUT', '标题长度必须在1-200个字符之间', 400);
    }
    updateData.title = updates.title.trim();
  }

  if (updates.content !== undefined) {
    if (typeof updates.content !== 'string' || updates.content.trim().length === 0) {
      throw new AppError('INVALID_INPUT', '内容不能为空', 400);
    }
    if (updates.content.length < 50 || updates.content.length > 5000) {
      throw new AppError('INVALID_INPUT', '内容长度必须在50-5000个字符之间', 400);
    }
    updateData.content = updates.content.trim();
  }

  if (updates.gradeLevel !== undefined) {
    const validGradeLevels = ['primary', 'middle', 'high'];
    if (!validGradeLevels.includes(updates.gradeLevel)) {
      throw new AppError('INVALID_INPUT', '年级级别必须是: primary, middle, high 之一', 400);
    }
    updateData.gradeLevel = updates.gradeLevel;
  }

  // 支持更新批改相关字段
  if (updates.status !== undefined) {
    const validStatuses = ['pending', 'processing', 'completed', 'failed'];
    if (!validStatuses.includes(updates.status)) {
      throw new AppError('INVALID_INPUT', '状态必须是: pending, processing, completed, failed 之一', 400);
    }
    updateData.status = updates.status;
  }

  if (updates.score !== undefined) {
    const score = Number(updates.score);
    if (isNaN(score) || score < 0 || score > 100) {
      throw new AppError('INVALID_INPUT', '分数必须在0-100之间', 400);
    }
    updateData.score = score;
  }

  if (updates.correctionResult !== undefined) {
    if (typeof updates.correctionResult !== 'object') {
      throw new AppError('INVALID_INPUT', '批改结果必须是对象', 400);
    }
    updateData.correctionResult = updates.correctionResult;
  }

  // 5. 更新作文（使用事务）
  const transaction = await sequelize.transaction();
  try {
    await essay.update(updateData, { transaction });
    await transaction.commit();

    // 6. 返回更新后的作文
    const updatedEssay = await Essay.findByPk(essayId, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'gradeLevel'],
        },
      ],
    });

    return {
      success: true,
      data: updatedEssay.toJSON(),
      message: '更新作文成功',
    };
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
};

/**
 * 删除作文
 * @param {string} essayId - 作文ID
 * @param {string} userId - 用户ID（用于权限验证）
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const deleteEssay = async (essayId, userId) => {
  // 1. 输入验证
  if (!essayId || typeof essayId !== 'string') {
    throw new AppError('INVALID_INPUT', '作文ID不能为空', 400);
  }

  if (!userId || typeof userId !== 'string') {
    throw new AppError('INVALID_INPUT', '用户ID不能为空', 400);
  }

  // 2. 查询作文
  const essay = await Essay.findByPk(essayId);
  if (!essay) {
    throw new AppError('ESSAY_NOT_FOUND', '作文不存在', 404);
  }

  // 3. 验证用户所有权
  if (essay.userId !== userId) {
    throw new AppError('FORBIDDEN', '无权删除此作文', 403);
  }

  // 4. 删除作文
  await essay.destroy();

  return {
    success: true,
    message: '删除作文成功',
  };
};

